package ldh.im.fxgui.rpc.router;

import javafx.application.Platform;
import ldh.im.dto.base.OkResp;
import ldh.im.dto.business.group.GroupAddReq;
import ldh.im.dto.business.group.GroupCreateReq;
import ldh.im.dto.business.group.GroupDelReq;
import ldh.im.dto.business.group.GroupExitReq;
import ldh.im.dto.business.server.ServerSendGroupInfoReq;
import ldh.im.fxbase.dao.ImSessionDao;
import ldh.im.fxbase.data.event.EventBusFactory;
import ldh.im.fxbase.data.event.SessionChange;
import ldh.im.fxbase.data.pojo.ImGroup;
import ldh.im.fxbase.data.pojo.ImSession;
import ldh.im.fxbase.service.ImGroupService;
import ldh.im.fxbase.util.BeanFactory;
import ldh.im.fxbase.util.FxThreadUtil;
import ldh.im.fxgui.util.UiUtil;
import ldh.rpc.util.JsonUtil;
import ldh.rpc.Rpc;
import ldh.rpc.RpcMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;

@Rpc
public class GroupConsumerRouter {

    private static final Logger LOGGER = LoggerFactory.getLogger(GroupConsumerRouter.class);

    private ImGroupService imGroupService = BeanFactory.getInstance().getBean(ImGroupService.class);
    private ImSessionDao sessionDao = BeanFactory.getInstance().getBean(ImSessionDao.class);

    /**
     * 接受服务端转发群创建
     * @param groupCreateReq
     * @return
     * @throws Exception
     */
    @RpcMapper(path="serverRedirectGroupCreate", asynHandle = true)
    public OkResp receiveGroupCreate(GroupCreateReq groupCreateReq) throws Exception {
        long time = Duration.between(groupCreateReq.getCreateDateTime(), LocalDateTime.now()).toMillis();
        LOGGER.info("收到服务端转发群创建信息，receive group create time: {}, data: {}", time, JsonUtil.toJson(groupCreateReq));
        String userId = UiUtil.getLoginImUser().getUserId();
        ImSession session = imGroupService.createGroup(userId, groupCreateReq);
        FxThreadUtil.runLater(()->{
            UiUtil.switchMessageSession(session);
        });
        return new OkResp();
    }

    /**
     * 接受服务端转发群邀请
     * @param groupAddReq
     * @return
     * @throws Exception
     */
    @RpcMapper(path="serverRedirectGroupAdd", asynHandle = true)
    public OkResp receiveGroupAdd(GroupAddReq groupAddReq) throws Exception {
        long time = Duration.between(groupAddReq.getCreateDateTime(), LocalDateTime.now()).toMillis();
        LOGGER.info("收到服务端转发群邀请信息，receive group add time: {}, data: {}", time, JsonUtil.toJson(groupAddReq));
        String userId = UiUtil.getLoginImUser().getUserId();
        ImSession imSession = imGroupService.addToGroup(userId, groupAddReq);
        EventBusFactory.getInstance().post(new SessionChange(imSession.getId()));
        return new OkResp();
    }

    /**
     * 接受服务端转发群退出
     * @param groupExitReq
     * @return
     * @throws Exception
     */
    @RpcMapper(path="serverRedirectGroupExit", asynHandle = true)
    public OkResp receiveGroupExit(GroupExitReq groupExitReq) throws Exception {
        long time = Duration.between(LocalDateTime.now(), groupExitReq.getCreateDateTime()).toMillis();
        LOGGER.info("收到服务端转发退群信息，receive time: {}, data: {}", time, JsonUtil.toJson(groupExitReq));
        String userId = UiUtil.getLoginImUser().getUserId();
        ImSession imSession = imGroupService.exitGroup(userId, groupExitReq);
//        EventBusFactory.getInstance().post(new SessionChange(imSession.getId()));
        return new OkResp();
    }

    /**
     * 接受服务端转发群删除
     * @param groupDelReq
     * @return
     * @throws Exception
     */
    @RpcMapper(path="serverRedirectGroupDel", asynHandle = true)
    public OkResp receiveGroupDel(GroupDelReq groupDelReq) throws Exception {
        long time = Duration.between(groupDelReq.getCreateDateTime(), LocalDateTime.now()).toMillis();
        LOGGER.info("收到服务端转发群删除信息，receive time: {}, data: {}", time, JsonUtil.toJson(groupDelReq));
        String userId = UiUtil.getLoginImUser().getUserId();
        imGroupService.delGroup(userId, groupDelReq);
        return new OkResp();
    }

    @RpcMapper(path="serverSendGroupInfo", asynHandle = true)
    public OkResp receiveGroupInfo(ServerSendGroupInfoReq groupInfoReq) throws Exception {
        long time = Duration.between(groupInfoReq.getCreateDateTime(), LocalDateTime.now()).toMillis();
        LOGGER.info("收到服务端群信息，receive time: {}, data: {}", time, JsonUtil.toJson(groupInfoReq));
        String userId = UiUtil.getLoginImUser().getUserId();
        imGroupService.saveOrUpdates(userId, Arrays.asList(groupInfoReq.getGroupInfoItem()), true);
        ImSession session = sessionDao.getByGroupCodeAndUserId(groupInfoReq.getGroupInfoItem().getGroupId(), userId);
        FxThreadUtil.runLater(()->{
            UiUtil.switchMessageSession(session);
        });
        return new OkResp();
    }
}
